package com.hd.trans.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.text.TextUtils;
import android.util.Log;

import androidx.activity.ComponentActivity;

import com.hd.trans.R;
import com.hd.trans.callback.OnCompletionListener;
import com.hd.trans.common.interf.IVoicePlayer;
import com.hd.trans.common.interf.VoiceComposeListener;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.ui.base.AppContextProvider;
import com.hd.trans.ui.component.HdTtsDownloadComponent;
import com.hd.trans.ui.component.TtsDownloadCallback;
import com.hd.trans.ui.service.VoicePlayService;
import com.hd.trans.widgets.VoicePlayView;

import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class VoicePlayUtil {
    private HdTtsDownloadComponent mTtsComponent;//  TTS组件
    private VoicePlayService mPlayerImp;//播放器控制
    private static HashMap<String,VoicePlayUtil> utilHashMap = new HashMap<>();
    private boolean isBind;//是否绑定了播放器服务：VoicePlayService
    private  String className;
    private OnCompletionListener listener;
    private MediaPlayer.OnCompletionListener completionListener;

    private VoicePlayUtil(String className) {
        this.className = className;
        initTtsComponent();
    }

    public static VoicePlayUtil getInstance(Class classObject){
        String className = classObject.getName();
        return getInstance(className);
    }

    public static VoicePlayUtil getInstance(String className){
        if(utilHashMap.containsKey(className)){
            return utilHashMap.get(className);
        }
        VoicePlayUtil voicePlayUtil = new VoicePlayUtil(className);
        utilHashMap.put(className,voicePlayUtil);
        return voicePlayUtil;
    }

    public static VoicePlayUtil getInstance(){
        String className = UUID.randomUUID().toString();
        return getInstance(className);
    }

    public IVoicePlayer getPlayerImp() {
        return mPlayerImp;
    }


    @Deprecated
    public void initTtsComponent(Context context){
        initTtsComponent();
    }

    public void initTtsComponent(){
        if(mTtsComponent == null || mTtsComponent.isDestroy()){
            mTtsComponent = new HdTtsDownloadComponent();
        }

        if(!isBind){
            bindVoicePlayService();
        }
    }

    @Deprecated
    public void releaseTtsComponent(ComponentActivity baseActivity){
        destroy();
    }

    public void destroy(){
        if(mTtsComponent != null && !mTtsComponent.isDestroy()){
            mTtsComponent.destroy();
        }
        if(isBind){
            unBindService();
        }
        utilHashMap.remove(className);
    }

    @Deprecated
    public void bindService(Context context){
        bindVoicePlayService();
    }

    @Deprecated
    public void bindService(){
        bindVoicePlayService();
    }

    public void bindVoicePlayService(){
        if(isBind){
            return;
        }
        mPlayerImp = new VoicePlayService();
        mPlayerImp.setOnCompletionListener(listener);
        mPlayerImp.setOnCompletionListener(completionListener);
        isBind = true;
    }


    @Deprecated
    public void unBindService(Context context){
        release();
    }

    @Deprecated
    public void unBindService(){
        release();
    }

    public void release(){
        if(!isBind){
            return;
        }
        if(mPlayerImp != null){
            mPlayerImp.release();
        }
        isBind = false;
    }

    public void startPlay(String file){
        if(isBind && mPlayerImp != null && !isPlaying()){
            mPlayerImp.startPlay(file);
        }
    }

    public void stopPlay(){
        if(isBind && mPlayerImp != null && isPlaying()){
            mPlayerImp.stopPlay();
        }
    }

    public boolean isPlaying(){
        if(isBind && mPlayerImp != null){
            return mPlayerImp.isPlaying();
        }
        return false;
    }

    public void setOnCompletionListener(OnCompletionListener listener){
        this.listener = listener;
        if(mPlayerImp != null){
            mPlayerImp.setOnCompletionListener(listener);
        }
    }

    public void setOnCompletionListener(MediaPlayer.OnCompletionListener listener){
        this.completionListener = listener;
        if(mPlayerImp != null){
            mPlayerImp.setOnCompletionListener(listener);
        }
    }

    /**
     * 删除语音合成文件
     */
    public void deleteTtsFile(TranslateRecord record,boolean isTransPart){
        mTtsComponent.deleteTtsFile(record, isTransPart, new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void deleteTtsFile(TranslateRecord record,boolean isTransPart,Observer<Boolean> observer){
        mTtsComponent.deleteTtsFile(record, isTransPart, observer);
    }

    /**
     * 删除所有TTS文件
     */
    public void deleteAllTtsFiles() {
        if(mTtsComponent == null || mTtsComponent.isDestroy()){
            return;
        }
        mTtsComponent.deleteAllTtsFiles(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void deleteAllTtsFiles(Observer<Boolean> observer) {
        if(mTtsComponent == null || mTtsComponent.isDestroy()){
            return;
        }
        mTtsComponent.deleteAllTtsFiles(observer);
    }

    /**
     * 执行语音合成并播放
     * voicePlayView 即将播放
     * mCurVoicePlayView 当前播放
     */
    public VoicePlayView executeTtsPlay(VoicePlayView voicePlayView,VoicePlayView mCurVoicePlayView, TranslateRecord record, boolean isTransPart) {
        return executeCompositeFile(voicePlayView,mCurVoicePlayView,record,isTransPart,null);
    }

    public VoicePlayView executeCompositeFile(VoicePlayView voicePlayView, VoicePlayView mCurVoicePlayView,
                                              TranslateRecord record, boolean isTransPart, VoiceComposeListener listener) {
        initTtsComponent();//初始化TTS组件

        if (voicePlayView == null || voicePlayView.isLoading()) {
            return mCurVoicePlayView;
        }

        //有时翻译会返回  ". "
        if (record == null || StringUtils.isEmpty(isTransPart?record.getContentTranslate():record.getContentOrig()))
            return mCurVoicePlayView;

        String wavTime = String.valueOf(record.getTriggerTime());
//        String content = record.getContentTranslate().trim();
        String ttsCode = null;
        if(isTransPart){
            ttsCode = record.getIsReverse() ? record.getLanguageFrom().getTtsCode() : record.getLanguageTo().getTtsCode();
        }else {
            ttsCode = record.getIsReverse() ? record.getLanguageTo().getTtsCode() : record.getLanguageFrom().getTtsCode();
        }
        if (StringUtils.isEmpty(ttsCode)) {
            ToastUtils.showError("该语言暂不支持语音播放");
            return mCurVoicePlayView;
        }
        if (isPlaying()) {
            stopPlay();
            if(mCurVoicePlayView != null && mCurVoicePlayView.isPlaying()){
                mCurVoicePlayView.stopPlay();
            }
            if(voicePlayView == mCurVoicePlayView){
                return mCurVoicePlayView;
            }
        }
        if (voicePlayView.isPlaying()) {
            mCurVoicePlayView = voicePlayView;
            voicePlayView.stopPlay();
            return mCurVoicePlayView;
        }

        if (mCurVoicePlayView != null && mCurVoicePlayView.isPlaying()) {
            mCurVoicePlayView.stopPlay();
        }
        mCurVoicePlayView = voicePlayView;

        String itemWavPath = FileUtils.getWavFileAbsolutePath(String.format(Locale.getDefault(), "%s_%s_%02d.wav", isTransPart,wavTime,
                PreferenceMgr.getInstance().getTranslatePreference().getVoiceSpeed()));

        File file = new File(itemWavPath);

        if (file.length() > 0) {
            voicePlayView.startPlay();
            startPlay(itemWavPath);
            if(listener != null) listener.onCompleted(itemWavPath, true);
        } else {
            voicePlayView.loading();
            final VoicePlayView finalMCurVoicePlayView = mCurVoicePlayView;
            mTtsComponent.stopAllDownload();//清空下载任务
            mTtsComponent.getTtsFile(record, isTransPart, itemWavPath, new TtsDownloadCallback() {
                @Override
                public void onCompleted() {
                    if (voicePlayView.equals(finalMCurVoicePlayView)) {
                        voicePlayView.startPlay();
                        startPlay(itemWavPath);
                    } else {
                        voicePlayView.stopPlay();
                    }
                    if(listener != null) listener.onCompleted(itemWavPath, false);
                    //更新到系统媒体库
                    File file = new File(itemWavPath);
                    MediaScannerConnection.scanFile(AppContextProvider.getContext(),
                            new String[]{file.toString()},
                            null, null);
                }

                @Override
                public void onDownloadFailed(int code, String msg) {
                    Log.i("onDownloadFailed", msg);
                    if (voicePlayView != null) {
                        voicePlayView.stopPlay();
                    }
                    ToastUtils.showError(R.string.tips_voice_download_failed);
                }

                @Override
                public void onMergeFailed(int code, String msg) {
                    Log.i("onMergeFailed", msg);
                    if (voicePlayView != null) {
                        voicePlayView.loadingFailed();
                        voicePlayView.stopPlay();
                    }
                    ToastUtils.showError(R.string.tips_voice_play_failed);
                }
            });
        }
        return mCurVoicePlayView;
    }

    public void executeCompositeFile(
            String ttsCode,
            String ttsContent,
            VoiceComposeListener listener) {

        initTtsComponent();//初始化TTS组件

        if (StringUtils.isEmpty(ttsCode)) {
            ToastUtils.showError("该语言暂不支持语音播放");
            return;
        }
        if(TextUtils.isEmpty(ttsContent)){
            ToastUtils.showNormal("文本内容为空");
            return;
        }

        String stringMd5 = FileMd5.getMD5String(ttsCode+ttsContent);//内容多了会比较耗时
        Log.i("liaoyucheng",stringMd5);

        String itemWavPath = FileUtils.getWavFileAbsolutePath(String.format(Locale.getDefault(), "%s_%02d.wav", stringMd5,
                PreferenceMgr.getInstance().getTranslatePreference().getVoiceSpeed()));

        File file = new File(itemWavPath);

        if (file.length() > 0) {
            if(listener != null) listener.onCompleted(itemWavPath, true);
        } else {
            if(listener != null) listener.onStarting();
            mTtsComponent.stopAllDownload();//清空下载任务
            mTtsComponent.getTtsFile(ttsCode, ttsContent, itemWavPath, new TtsDownloadCallback() {
                @Override
                public void onCompleted() {
                    if(listener != null) listener.onCompleted(itemWavPath, false);
                    //更新到系统媒体库
                    File file = new File(itemWavPath);
                    MediaScannerConnection.scanFile(AppContextProvider.getContext(),
                            new String[]{file.toString()},
                            null, null);
                }

                @Override
                public void onDownloadFailed(int code, String msg) {
                    if(listener != null) listener.onDownloadFailed();
                    ToastUtils.showError(R.string.tips_voice_download_failed);
                }

                @Override
                public void onMergeFailed(int code, String msg) {
                    if(listener != null) listener.onDownloadFailed();
                    ToastUtils.showError(R.string.tips_voice_play_failed);
                }
            });
        }
    }

}
